<?php
/**
 * @project kkzc
 * @date 2015-7-10
 * @author xialei <xialeistudio@gmail.com>
 */

namespace app\services;


use app\components\CommonTool;
use app\components\Service;
use app\exception\ErrorCode;
use app\models\Order;
use app\models\User;
use yii\base\Exception;

/**
 * 订单业务类
 * @author xialei <xialeistudio@gmail.com>
 * Class OrderService
 * @package app\services
 */
class OrderService extends Service
{
    const KEY = 'kkzc2015fx';
    const HOST = 'http://www.kuaikuaizuche.com';

    /**
     * @author xialei <xialeistudio@gmail.com>
     * @param string $className
     * @return self
     */
    public static function instance($className = __CLASS__)
    {
        if (empty(self::$_instance[$className])) {
            self::$_instance[$className] = new $className();
        }
        return self::$_instance[$className];
    }

    /**
     * 获取远程用户
     * @author xialei <xialeistudio@gmail.com>
     * @param $phone
     * @param bool $async 是否同步到本地
     * @return mixed
     * @throws Exception
     */
    public function getRemoteUser($phone, $async = true)
    {
        if (!CommonTool::isPhone($phone)) {
            throw new Exception(\Yii::t('app', 'phone invalid'), ErrorCode::PHONE_INVALID);
        }
        $params = [
            'phone' => $phone,
            'timestamp' => time()
        ];

        $sign = md5(self::KEY . $params['timestamp']);
        $params['signature'] = $sign;
        $data = $this->get(self::HOST . '/kkzc/otherapi/findUserByPhone.do', $params);
        $data = json_decode($data, true);
        if ($data['code'] != 0) {
            throw new Exception($data['msg'], $data['code']);
        }
        //同步到本地
        if ($async) {
            /** @var User $user */
            $user = User::find()->where(['phone' => $phone])->one();
            if (!empty($user)) {
                $user->realname = $data['userName'];
                $user->role = $data['loginType'];
                $user->save();
            }
        }
        return $data;
    }

    /**
     * 获取用户订单远程
     * @author xialei <xialeistudio@gmail.com>
     * @param $userId
     * @param int $cursor
     * @return mixed
     * @throws Exception
     */
    public function getOrders($userId, $cursor = 0)
    {
        /** @var User $user */
        $user = User::findOne($userId);
        if (empty($user)) {
            throw new Exception(\Yii::t('app', 'user not found'), ErrorCode::USER_NOT_FOUND);
        }
        if (empty($user->phone)) {
            throw new Exception(\Yii::t('app', 'user phone empty'), ErrorCode::USER_PHONE_EMPTY);
        }
        //查找本地库中最新的一条订单创建时间
        if ($cursor == 0) {
            $latest = Order::find()->where(['user_id' => $userId])->orderBy(['created_at' => SORT_DESC])->select(['created_at'])->scalar();
            if ($latest > 0) {
                $cursor = $latest;
            }
        }
        //请求远程接口
        $params = [
            'phone' => $user->phone,
            'timestamp' => time()
        ];
        if ($cursor > 0) {
            $params['createTime'] = date('Y/m/d H:i:s', $cursor);
        }else{
            $params['createTime'] = '';
        }
        $sign = md5(self::KEY . $params['timestamp']);
        $params['signature'] = $sign;
        $data = $this->get(self::HOST . '/kkzc/otherapi/findOrderByPhone.do', $params);
        $data = json_decode($data, true);
        if ($data['code'] != 0) {
            throw new Exception($data['msg'], $data['code']);
        }
        return $data;
    }
}